<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="借货编号" prop="loanNo">
        <el-input
          v-model="queryParams.loanNo"
          placeholder="请输入借货编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目ID" prop="projectId">
        <el-input
          v-model="queryParams.projectId"
          placeholder="请输入项目ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出借时间" prop="loanTime">
        <el-date-picker clearable
                        v-model="queryParams.loanTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择出借时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="出借物品ID" prop="itemId">
        <el-input
          v-model="queryParams.itemId"
          placeholder="请输入出借物品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出借物品数量" prop="itemQty">
        <el-input
          v-model="queryParams.itemQty"
          placeholder="请输入出借物品数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="出借对象" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入出借对象"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审批人" prop="approver">
        <el-input
          v-model="queryParams.approver"
          placeholder="请输入审批人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="归还时间" prop="rerunTime">
        <el-date-picker clearable
                        v-model="queryParams.rerunTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择归还时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fm:la:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fm:la:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="loanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="借货编号" align="center" prop="loanNo" />
      <el-table-column label="项目名称" align="center" prop="project.projectName" />
      <el-table-column label="出借时间" align="center" prop="loanTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.loanTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出借物品" align="center" prop="inventory.itemName" />
      <el-table-column label="出借数量" align="center" prop="itemQty" />
      <el-table-column label="出借对象" align="center" prop="user.userName" />
      <el-table-column label="审批意见" align="center" prop="approveOpinion" />
      <el-table-column label="状态" align="center" prop="status">
      <template slot-scope="scope">
        <dict-tag :options="dict.type.fm_la_status" :value="scope.row.status" :dictName="scope.row.status" />
      </template>
      </el-table-column>
      <el-table-column label="归还时间" align="center" prop="rerunTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.rerunTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fm:la:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fm:la:del']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改借货管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
        <el-form-item label="借货编号" prop="loanNo">
          <el-input v-model="form.loanNo" placeholder="系统生成" disabled />
        </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目编号" prop="projectNo">
              <el-input v-model="form.projectNo" placeholder="根据项目自动匹配" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 1. 修正项目选择器的v-model绑定 -->
            <el-form-item label="项目名称" prop="projectId">
              <el-select
                v-model="form.projectId"
                placeholder="请选择项目"
                @change="handleProjectChange"
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
        <el-form-item label="出借物品" prop="itemId">
          <el-select
            v-model="form.itemId"
            placeholder="请选择出借物品名称"
            @change="handleItemChange"
          >
            <el-option
              v-for="item in inventoryList"
              :key="item.id"
              :label="item.itemName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
          </el-col>
          <el-col :span="8">
        <el-form-item label="出借数量" prop="itemQty">
          <el-input v-model="form.itemQty" placeholder="请输入出借物品数量" />
        </el-form-item>
          </el-col>
          <el-col :span="8">
        <el-form-item label="出借对象" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入出借对象" />
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系方式" />
        </el-form-item>
          </el-col>
          <el-col :span="8">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
          </el-col>
          <el-col :span="8">
        <el-form-item label="审批人" prop="approver">
          <el-input v-model="form.approver" placeholder="请输入审批人" />
        </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
          <el-form-item label="预计归还时间" prop="rerunTime" label-width="50">
            <el-date-picker clearable
                            v-model="form.rerunTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择归还时间">
            </el-date-picker>
          </el-form-item>
          </el-col>
          </el-row>
          <el-row>
          <el-col :span="12">
        <el-form-item label="审批意见" prop="approveOpinion">
          <el-input v-model="form.approveOpinion" type="textarea" placeholder="请输入内容" disabled/>
        </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="12" align="">
            <el-button v-if="isSub" type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="cancel">取 消</el-button>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLoan, getLoan, delLoan, addLoan, updateLoan } from "@/api/system/fm/la"
import dict from "@/utils/dict";
import {getAllProject} from "@/api/pm/projects";
import {getAllInventory} from "@/api/system/inventory";

export default {
  name: "Loan",
  dicts:['fm_la_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 借货管理表格数据
      loanList: [],
      projectList: [],
      inventoryList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isSub: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        loanNo: null,
        projectId: null,
        loanTime: null,
        itemId: null,
        itemName: null,
        itemQty: null,
        userId: null,
        contact: null,
        approver: null,
        approveOpinion: null,
        status: null,
        rerunTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        approver: [
          { required: true, message: "审批人不能为空", trigger: "blur" }
        ],
        loanTime: [
          { required: true, message: "出借时间不能为空", trigger: "blur" }
        ],
        itemName: [
          { required: true, message: "出借物品名称不能为空", trigger: "blur" }
        ],
        itemQty: [
          { required: true, message: "出借物品数量不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "出借对象不能为空", trigger: "blur" }
        ],
        contact: [
          { required: true, message: "联系方式不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
    this.loadProjectOptions()
    this.loadInventoryOptions().then(() => {
      // 调试：打印加载的物品列表
      console.log("加载的物品列表：", this.inventoryList);
    });
  },
  methods: {
    dict,
    /** 查询借货管理列表 */
    getList() {
      this.loading = true
      listLoan(this.queryParams).then(response => {
        this.loanList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        loanNo: null,
        projectId: null,
        loanTime: null,
        itemId: null,
        itemName: null,
        itemQty: null,
        userId: null,
        contact: null,
        remark: null,
        approver: null,
        approveOpinion: null,
        status: null,
        rerunTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    loadInventoryOptions() {
      getAllInventory().then(response => {
        // 关键调整：根据实际接口返回结构处理
        // 如果后端直接返回数组（如你提供的JSON），则直接赋值
        this.inventoryList = response || [];
        // 如果后端返回格式是{data: 数组}，则用原来的this.inventoryList = response.data || [];
      }).catch(err => {
        console.error('加载库存列表失败', err);
      })
    },
    handleItemChange(val){
      if (!val) {
        this.form.itemName = "";
        return;
      }
      const selectedItem = this.inventoryList.find(item => item.id === val);
      if (selectedItem) {
        this.form.itemName = selectedItem.itemName || "";
      } else {
        this.form.itemName = "";
      }
    },
    loadProjectOptions() {
      getAllProject().then(response => {
        // 正确写法：从response中提取data字段的数组
        this.projectList = response.data || [];  // 关键修复：添加 .data
      }).catch(err => {
        console.error('加载项目列表失败', err);
      })
    },
    // 2. 处理项目选择变化（核心联动逻辑）
    handleProjectChange(val) {
      if (!val) {
        this.form.projectNo = "";
        return;
      }
      // 从项目列表中找到选中的项目
      const selectedProject = this.projectList.find(item => item.id === val);
      if (selectedProject) {
        // 自动填充项目编号
        this.form.projectNo = selectedProject.projectNo || "";
      } else {
        this.form.projectNo = "";
      }
    },
    // 查看操作：handleView 方法
    handleView(row) {
      this.reset()
      this.open = true
      this.isApprovalView = true;
      this.isSub = false
      this.title = "查看借货申请"
      this.form = {...row}
      // 新增：映射出借物品名称
      this.form.itemName = row.inventory?.itemName || ''; // 从inventory对象提取
      // 处理项目信息回显 - 关键修复：使用row.projectId而非row.project.id
      this.form.projectId = row.projectId;  // 直接使用报销表中的projectId
      this.form.projectNo = row.project?.projectNo || ''; // 从project对象提取
      this.form.projectName = row.project?.projectName || ''; // 从project对象提取
      // 从项目列表中找到对应的项目信息
      const project = this.projectList.find(p => p.id === row.projectId);
      if (project) {
        this.form.projectNo = project.projectNo;
        this.form.projectName = project.projectName;
      }
      // 新增：从user对象中提取userName
      this.form.userName = row.user?.userName || ''
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.isSub= true
      this.open = true
      this.title = "添加借货管理"
    },
    // 修改操作：handleUpdate 方法
    handleUpdate(row) {
      this.reset()
      this.isSub = true
      const id = row.id || this.ids
      getLoan(id).then(response => {
        this.form = response.data
        // 新增：映射出借对象名称
        this.form.userName = response.data.user?.userName || ''; // 从user对象提取
        // 新增：映射出借物品名称
        this.form.itemName = response.data.inventory?.itemName || ''; // 从inventory对象提取
        this.form.projectNo = response.data.project?.projectNo || ''; // 从project对象提取
        this.form.projectName = response.data.project?.projectName || ''; // 从project对象提取

        this.open = true
        this.title = "修改借货管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLoan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addLoan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除借货管理编号为"' + ids + '"的数据项？').then(function() {
        return delLoan(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fm/la/export', {
        ...this.queryParams
      }, `loan_${new Date().getTime()}.xlsx`)
    }
  },
  // 3. 监听项目ID变化，确保联动生效
  watch: {
    'form.projectId'(val) {
      this.handleProjectChange(val);
    },
    'form.itemId'(val) {
      this.handleItemChange(val);
    }
  }
}

</script>
